package com.atguigu.guli.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectExcelData;
import com.atguigu.guli.service.edu.listener.SubjectDataListener;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-06-23
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Autowired
    SubjectMapper subjectMapper;
    @Override
    public void importFile(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream())
                    .registerReadListener(new SubjectDataListener(subjectMapper))
                    .head(SubjectExcelData.class)
                    .sheet(0)
                    .doRead();


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<Subject> getSubjectList() {
        //创建一个map用来存储对象
        HashMap<String, Subject> map = new HashMap<>();
        //查询全部数据
        List<Subject> subjectList = subjectMapper.selectList(null);
        for (Subject subject : subjectList) {
            //把一级数据调出来
            if(subject.getParentId().equals("0")){
                //subject.getId作为key,因为这个是唯一的
                map.put(subject.getId(), subject);
            }
            //如果父id不等于0的话就是二级分类
            if(!subject.getParentId().equals("0")){
                //获取存到map里的一级对象
                Subject sub = map.get(subject.getParentId());
                List<Subject> subjects = sub.getSubjects();
                subjects.add(subject);

            }
        }
        return new ArrayList<Subject>(map.values());

    }
}
